//
//  CZHomeVC.m
//  XinLang_OC
//
//  Created by WONG on 16/2/20.
//  Copyright © 2016年 cheuhui. All rights reserved.
//

#import "CZHomeVC.h"
#import "UIBarButtonItem+Extension.h"
#import "IWTitleButton.h"
#import "CZUserAccount.h"
#import "CZStatus.h"
#import "CZStatusCell.h"
#import "CZStatusNormalCell.h"
#import "CZStatusForwardCell.h"
#import "CZRefreshControl.h"
#import "MJRefresh.h"
#import "PhotoBrowserVC.h"

#import "CZSQLiteManager.h"


@interface CZHomeVC ()

@property (nonatomic,strong) NSMutableArray *statuses;

/**
 *  提示加载了多少条微博
 */
@property (nonatomic,strong) UILabel *tipLabel;

@end

@implementation CZHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [CZSQLiteManager sharedManager];
    
    [self setupNav];
    
    [self prepareTableView];
    //[self loadStatus];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectedPicture:) name:CZPictureViewSelectedPictureNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)selectedPicture:(NSNotification *)notification {
    // 获取大图URL数组
    NSArray *models = notification.userInfo[CZPictureViewSelectedPictureModelKey];
    
    // 获取点击配图的图片indexPath
    NSIndexPath *indexpath = notification.userInfo[CZPictureViewSelectedPictureIndexPathKey];
    
    if (!models || !indexpath) {
        return;
    }
    
    PhotoBrowserVC *browserVC = [[PhotoBrowserVC alloc] initWithModels:models indexPath:indexpath];
    
    // 自定义转场动画
    // 让 PhotoBrowserVC 来充当 转场的代理,不依赖首页控制器
    browserVC.transitioningDelegate = browserVC;
    browserVC.modalPresentationStyle = UIModalPresentationCustom;
    
    [self presentViewController:browserVC animated:YES completion:nil];
}

// 下拉刷新，加载新的微博数据
- (void)loadNewStatus {
    // 当第一次进入程序的时候 statuses 为 nil. since_id = 0,加载最新的20条微博数据
    // 当有数据来下拉刷新,获取到第一条微博(第一条微博id最大).返回的数据,就是比第一条微博id还大的微博,就是新数据
    
    CZStatus *status = self.statuses.firstObject;
    NSNumber *since_id = status.id;

    NSLog(@"since_id = %@",since_id);

    // 加载微博数据
    [CZStatus loadStatus:since_id max_id:0 finished:^(NSMutableArray *statuses, NSError *error) {
        // 不管有没有获得数据，都关掉刷新控件
        [self.refreshControl endRefreshing];
        
        if (error != nil ) {
            NSLog(@"加载微博数据失败error = %@",error);
            [SVProgressHUD showErrorWithStatus:@"网络不给力"];
            return;
        }
        //NSLog(@"加载微博数据成功statuses = %@",statuses);
        
        NSUInteger count = statuses.count;
        NSLog(@"加载到的微博数据：count = %zd",count);
        
        if (since_id > 0) {
            [self showTipView:count];
        }
        
        // 需要判断是下拉刷新,还是第一次加载20条数据
        if (count == 0) {
            // 没有新的数据
            return;
        }
        
        if (since_id > 0) {
            // 把新加载的数据添加到最后去了
            //[self.statuses addObjectsFromArray:statuses];
            
            [statuses addObjectsFromArray:self.statuses];
            self.statuses = statuses;

            NSLog(@"加载到新的数据,拼接到现有数据的前面,总共%zd条数据",self.statuses.count);
        } else {
            self.statuses = statuses;
            
            NSLog(@"首次加载最新%zd条微博数据",self.statuses.count);
        }
        [self.tableView reloadData];
    }];
}

// 上拉刷新，加载更多微博数据
- (void)loadMoreStatus {
    CZStatus *status = self.statuses.lastObject;
    NSNumber *max_id = status.id;
    NSLog(@"mas_id = %@",max_id);
    
    [CZStatus loadStatus:0 max_id:max_id finished:^(NSMutableArray *statuses, NSError *error) {
        // 加载完数据，结束上拉加载更多数据，让菊花停止旋转
        
        if (statuses.count == 0) {
            [SVProgressHUD showErrorWithStatus:@"没有加载到更多数据"];
            return;
        }
        
        [self.statuses addObjectsFromArray:statuses];
        [self.tableView reloadData];
    }];
    NSLog(@"上拉加载数据完成，总共有：%zd条数据",self.statuses.count);
}

- (void)showTipView:(NSInteger)count {
    self.tipLabel.text = count == 0 ? @"没有获取到数据" : [NSString stringWithFormat:@"加载了%zd条微博",count];
    
    [UIView animateWithDuration:1 animations:^{
        
        self.tipLabel.y = 44;
        
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 animations:^{
            
            self.tipLabel.y = -64;
            
        }];
    }];
}


- (void)setupNav {
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" target:self action:@selector(friendsearch)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" target:self action:@selector(pop)];
    
    IWTitleButton *titleButton = [[IWTitleButton alloc] init];
    
    CZUserAccount *userAccount = [CZUserAccount loadUserAccount];
    if (userAccount.screen_name) {
        [titleButton setTitle:userAccount.screen_name forState:UIControlStateNormal];
    }else {
        [titleButton setTitle:@"微博首页" forState:UIControlStateNormal];
    }
    
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [titleButton sizeToFit];
    
    self.navigationItem.titleView = titleButton;
}

- (void)prepareTableView {
    __weak typeof(self) weakSelf = self;
    
    // 这里一定要注册cell，不然计算不了行高
    // 注册cell,需要注册2个,根据显示的模型返回对应类型的cell
    [self.tableView registerClass:[CZStatusNormalCell class] forCellReuseIdentifier:NormalCell];
    [self.tableView registerClass:[CZStatusForwardCell class] forCellReuseIdentifier:ForwardCell];
    
    // 设置预估行高,减少cell的计算次数,加载cell内容的显示.缺点:没有显示的cell,在即将显示的时候,还是需要计算一次cell,有可能影响,拖动的流畅
    self.tableView.estimatedRowHeight = 200;
    // 根据cell的约束来自动确定cell的高度UITableViewAutomaticDimension
    //self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    // 默认大小: 宽度等于屏幕的宽度,高度是60
    self.refreshControl = [[CZRefreshControl alloc] init];
    
    // 当刷新控件进入刷新状态时调用
    [self.refreshControl addTarget:self action:@selector(loadNewStatus) forControlEvents:UIControlEventValueChanged];
    
    // 主动开始刷新数据
    // beginRefreshing只会让刷新控件进入刷新状态,并不会触发UIControlEvents.ValueChanged事件
    [self.refreshControl beginRefreshing];
    
    // 代码触发refreshControl控件的UIControlEvents.ValueChanged
    [self.refreshControl sendActionsForControlEvents:UIControlEventValueChanged];
    
    /*
        使用 MJRefresh 来上拉加载更多数据
     */
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        // 网络加载数据,添加数据
//        [self loadMoreStatus];
//        // 结束刷新
//        [weakSelf.tableView.mj_footer endRefreshing];
//    }];
    
}

#pragma mark - BarButtonItem selector
- (void)friendsearch {
    
}
- (void)pop {

}

static NSString *NormalCell = @"NormalCell";
static NSString *ForwardCell = @"ForwardCell";
#pragma mark - UITableViewSourceData && UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.statuses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZStatus *status = self.statuses[indexPath.row];
    
    CZStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:status.cellId];
    
    // 注册cell之后 不需要这一步
//    if (!cell) {
//        cell = [[CZStatusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HomeIdentifier];
//    }
    
    cell.status =status;
    
    return cell;
}

/// 返回对应cell的行高
/// 发现行高调用比较频繁,导致多次调用.计算一次,然后保存起来,下次直接返回缓存的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 先看看有没有缓存的行高,如果有缓存行高,直接拿来用,没有的话,在计算,并缓存起来
    CZStatus *status = self.statuses[indexPath.row];
    
    if (status.rowHeight != 0) {
        //NSLog(@"返回缓存的行高rowHeight = %f",status.rowHeight);
        return status.rowHeight;
    }
    // 能到下面来说明没有缓存的行高，那么就计算行高，再缓存行高
    CZStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:status.cellId];
    // 计算行高
    CGFloat rowHeight = [cell rowHeight:status];
    //NSLog(@"rowHeight = %f",rowHeight);
    // 缓存行高
    status.rowHeight = rowHeight;
    
    return rowHeight;
}

/*
    UITableView告别手动上拉更新,自动刷新数据
    当tableView滚动到 倒数第五条 时就 加载更多数据
 */
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 当前微博数量
    NSInteger statusCount = self.statuses.count;
    
    if (indexPath.row == statusCount - 6) {
        NSLog(@"倒数第五条 row = %zd",indexPath.row);
        
        // 网络加载更多数据,添加数据
        [self loadMoreStatus];
    }
}



#pragma mark - lazy load

- (NSMutableArray *)statuses {
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}

- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -64, ScreenWidth, 44)];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.textColor = [UIColor whiteColor];
        _tipLabel.font = [UIFont systemFontOfSize:16];
        _tipLabel.backgroundColor = [UIColor orangeColor];
        // 添加到导航栏的最底部
        [self.navigationController.navigationBar insertSubview:_tipLabel atIndex:0];
    }
    return _tipLabel;
}


@end









